package com.sxkiler.demo.solr;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class SolrSearchUtil
{
    private static Logger logger = LoggerFactory.getLogger(SolrSearchUtil.class);
    private static final String isUserSolr = "1";

    public static boolean updateTableSolr(String solrUrl, String solrCore, String table, String isClear)
            throws Exception
    {
        String url = solrUrl + "/" + solrCore + "/dataimport?indent=on&wt=json";
        HttpPost post = new HttpPost(url);
        List<BasicNameValuePair> params = new ArrayList();
        params.add(new BasicNameValuePair("command", "full-import"));
        params.add(new BasicNameValuePair("verbose", "false"));
        params.add(new BasicNameValuePair("clean", isClear));
        params.add(new BasicNameValuePair("commit", "true"));
        params.add(new BasicNameValuePair("optimize", "false"));
        params.add(new BasicNameValuePair("core", solrCore));
        params.add(new BasicNameValuePair("entity", table));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
        post.setEntity(entity);

        CloseableHttpClient client = HttpClients.createDefault();
        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() == 200)
        {
            String responseStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            logger.info("this.response  :" + responseStr);

            JSONObject obj = JSONObject.parseObject(responseStr);
            Object status = obj.get("status");
            status = "";
            while (!"idle".equals(status))
            {
                logger.info("this.response command full-import:" + status + " " + table);
                Thread.sleep(5000L);
                status = getIndexUpdateStatus(solrUrl, solrCore);
            }
            return true;
        }
        return true;
    }

    private static Object getIndexUpdateStatus(String solrUrl, String solrCore)
            throws Exception
    {
        String url = solrUrl + "/" + solrCore + "/dataimport?command=status&indent=on&wt=json";
        HttpGet post = new HttpGet(url);

        CloseableHttpClient client = HttpClients.createDefault();
        HttpResponse response = client.execute(post);
        Object status = "";
        if (response.getStatusLine().getStatusCode() == 200)
        {
            String responseStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            JSONObject obj = JSONObject.parseObject(responseStr);
            status = obj.get("status");
        }
        return status;
    }

//    public static Map<String, Object> solrRoomOrCustomerSearch(String searchPhrase, String projectID, String roomParam, String customerParam, String contractParam, String isUseSolr)
//    {
//        String rows = "500";
//        return solrRoomOrCustomerSearch(searchPhrase, projectID, roomParam, customerParam, contractParam, rows, isUseSolr);
//    }

//    public static Map<String, Object> solrRoomOrCustomerSearch(String searchPhrase, String projectID, String roomParam, String customerParam, String contractParam, String rows, String isUseSolr)
//    {
//        Map<String, Object> resultMap = new HashMap(16);
//        if (!"1".equals(isUseSolr))
//        {
//            resultMap.put("isSolr", Integer.valueOf(0));
//            return resultMap;
//        }
//        StringBuilder sb = new StringBuilder();
//        try
//        {
//            if (!StringUtils.isEmpty(searchPhrase))
//            {
//                String checkSearch = searchPhrase;
//                searchPhrase = ClientUtils.escapeQueryChars(searchPhrase).toLowerCase();
//
//                List<String> roomIdList = new ArrayList();
//                List<String> customerIdList = new ArrayList();
//                List<String> contractIdList = new ArrayList();
//                List<String> contractNoList = new ArrayList();
//                if ((roomParam != null) && (!"".equals(roomParam))) {
//                    roomIdList = solrRoomSearch(checkSearch, projectID, roomParam, rows);
//                }
//                if ((customerParam != null) && (!"".equals(customerParam))) {
//                    customerIdList = solrCustomerSearch(checkSearch, projectID, customerParam, rows);
//                }
//                if ((contractParam != null) && (!"".equals(contractParam))) {
//                    contractIdList = solrContractSearch(checkSearch, projectID, contractParam, rows);
//                }
//                if ((contractParam != null) && (!"".equals(contractParam)))
//                {
//                    String[] contractNoArray = searchPhrase.split(",");
//                    for (String contractArray : contractNoArray) {
//                        contractNoList.add(contractArray.trim());
//                    }
//                }
//                if (LogicUtils.isNotNullAndEmpty(roomIdList))
//                {
//                    resultMap.put("roomIdList", roomIdList);
//                    logger.info("logroomIdList:" + roomIdList.size());
//                }
//                if (LogicUtils.isNotNullAndEmpty(customerIdList))
//                {
//                    resultMap.put("customerIdList", customerIdList);
//                    logger.info("logcustomerIdList:" + customerIdList.size());
//                }
//                if (LogicUtils.isNotNullAndEmpty(contractIdList))
//                {
//                    resultMap.put("contractIdList", contractIdList);
//                    logger.info("logcontractIdList:" + contractIdList.size());
//                }
//                else
//                {
//                    resultMap.put("contractIdList", new ArrayList());
//                }
//                if (LogicUtils.isNotNullAndEmpty(contractNoList))
//                {
//                    resultMap.put("contractNoList", contractNoList);
//                    logger.info("logcontractNoList:" + contractNoList.size());
//                }
//                resultMap.put("isSolr", Integer.valueOf(1));
//            }
//            else
//            {
//                resultMap.put("isSolr", Integer.valueOf(0));
//            }
//        }
//        catch (Exception e)
//        {
//            logger.error("error", e);
//            resultMap.put("isSolr", Integer.valueOf(0));
//        }
//        return resultMap;
//    }

//    public static List<String> solrRoomSearch(String checkSearch, String projectID, String roomParam, String rows)
//            throws Exception
//    {
//        String searchPhrase = ClientUtils.escapeQueryChars(checkSearch).toLowerCase();
//        StringBuilder sb = new StringBuilder();
//        Map<String, String> parMap = new HashMap();
//        parMap.put("start", "0");
//        parMap.put("rows", rows);
//
//        String[] roomArray = roomParam.split(",");
//        for (int i = 0; i < roomArray.length; i++)
//        {
//            if ("roomName".equals(roomArray[i])) {
//                sb.append(roomArray[i]).append(":").append(searchPhrase).append("^5 OR ").append(roomArray[i]).append(":*").append(searchPhrase).append("*^5");
//            } else {
//                sb.append(roomArray[i]).append(":").append(searchPhrase).append(" OR ").append(roomArray[i]).append(":*").append(searchPhrase).append("*");
//            }
//            if ((roomArray.length > 1) && (i != roomArray.length - 1)) {
//                sb.append(" OR ");
//            }
//        }
//        int i;
//        if (projectID.indexOf(",") != -1)
//        {
//            List<String> projectIDList = Arrays.asList(projectID.split(","));
//            StringBuilder projectSb = new StringBuilder();
//            projectSb.append("roomProjectID:").append((String)projectIDList.get(0));
//            for (i = 1; i < projectIDList.size(); i++) {
//                projectSb.append(" OR roomProjectID:").append((String)projectIDList.get(i));
//            }
//            parMap.put("q", "(" + projectSb.toString() + ") AND (" + sb.toString() + ")");
//        }
//        else
//        {
//            parMap.put("q", "roomProjectID:" + projectID + " AND (" + sb.toString() + ")");
//        }
//        parMap.put("fl", "id," + roomParam);
//
//        List<Map<String, Object>> roomList = SolrManager.queryDocs(parMap);
//        List<String> roomIdList = new ArrayList();
//        logger.info("logroomList:" + roomList.size());
//        for (Map<String, Object> map : roomList)
//        {
//            Iterator<Map.Entry<String, Object>> it2 = map.entrySet().iterator();
//            while (it2.hasNext())
//            {
//                Map.Entry<String, Object> me = (Map.Entry)it2.next();
//                if (String.valueOf(me.getValue()).contains(checkSearch))
//                {
//                    roomIdList.add(String.valueOf(map.get("id")));
//                    break;
//                }
//            }
//        }
//        return roomIdList;
//    }

//    public static List<String> solrCustomerSearch(String checkSearch, String projectID, String customerParam, String rows)
//            throws Exception
//    {
//        String searchPhrase = ClientUtils.escapeQueryChars(checkSearch).toLowerCase();
//        long start = System.currentTimeMillis();
//        StringBuilder sb = new StringBuilder();
//        Map<String, String> parMap = new HashMap();
//        parMap.put("start", "0");
//
//        parMap.put("rows", rows);
//
//        String[] customerArray = customerParam.split(",");
//        for (int i = 0; i < customerArray.length; i++)
//        {
//            sb.append(customerArray[i]).append(":").append(searchPhrase).append(" OR ").append(customerArray[i]).append(":*").append(searchPhrase).append("*");
//            if ((customerArray.length > 1) && (i != customerArray.length - 1)) {
//                sb.append(" OR ");
//            }
//        }
//        parMap.put("fl", "id," + customerParam);
//        int i;
//        if (projectID.indexOf(",") != -1)
//        {
//            List<String> projectIDList = Arrays.asList(projectID.split(","));
//            StringBuilder projectSb = new StringBuilder();
//            projectSb.append("customerProjectID:").append((String)projectIDList.get(0));
//            for (i = 1; i < projectIDList.size(); i++) {
//                projectSb.append(" OR customerProjectID:").append((String)projectIDList.get(i));
//            }
//            parMap.put("q", "(" + projectSb.toString() + ") AND (" + sb.toString() + ")");
//        }
//        else
//        {
//            parMap.put("q", "customerProjectID:" + projectID + " AND (" + sb.toString() + ")");
//        }
//        List<Map<String, Object>> customerList = SolrManager.queryDocs(parMap);
//        logger.info("����������" + parMap);
//        logger.info("������" + (System.currentTimeMillis() - start));
//        logger.info("logcustomerList��" + customerList.size());
//        logger.info("logcustomerList��" + customerList);
//        List<String> customerIdList = new ArrayList();
//        for (Map<String, Object> map : customerList)
//        {
//            Iterator<Map.Entry<String, Object>> it2 = map.entrySet().iterator();
//            while (it2.hasNext())
//            {
//                Map.Entry<String, Object> me = (Map.Entry)it2.next();
//                if (String.valueOf(me.getValue()).contains(checkSearch))
//                {
//                    customerIdList.add(String.valueOf(map.get("id")));
//                    break;
//                }
//            }
//        }
//        logger.info("logcustomerList��" + customerIdList);
//        return customerIdList;
//    }

//    public static Map<String, Object> solrContractOrParkSearch(String searchPhrase, String projectID, String parkingParam, String contractParam, String isUseSolr)
//    {
//        Map<String, Object> resultMap = new HashMap();
//        StringBuilder sb = new StringBuilder();
//        if (!"1".equals(isUseSolr))
//        {
//            resultMap.put("isSolr", Integer.valueOf(0));
//            return resultMap;
//        }
//        try
//        {
//            if (StringUtils.isEmpty(searchPhrase))
//            {
//                resultMap.put("isSolr", Integer.valueOf(0));
//                return resultMap;
//            }
//            String checkSearch = searchPhrase;
//            searchPhrase = ClientUtils.escapeQueryChars(searchPhrase).toLowerCase();
//
//            List<String> customerIdList = new ArrayList();
//            long start = System.currentTimeMillis();
//            String[] contractArray;
//            if ((contractParam != null) && (!"".equals(contractParam)))
//            {
//                Map<String, String> parMap = new HashMap();
//
//                parMap.put("start", "0");
//
//                parMap.put("rows", "300");
//                contractArray = contractParam.split(",");
//                sb.append(contractArray[0]).append(":").append(searchPhrase).append(" OR ").append(contractArray[0]).append(":*").append(searchPhrase).append("*");
//                parMap.put("q", "contractProjectID:" + projectID + " AND (" + sb.toString() + ")");
//                parMap.put("fl", "id," + contractArray[1]);
//
//                List<Map<String, Object>> contractList = SolrManager.queryDocs(parMap);
//                logger.info("logroomList:" + contractList.size());
//                for (Map<String, Object> map : contractList)
//                {
//                    Iterator<Map.Entry<String, Object>> it2 = map.entrySet().iterator();
//                    while (it2.hasNext())
//                    {
//                        Map.Entry<String, Object> me = (Map.Entry)it2.next();
//                        if (String.valueOf(me.getKey()).contains(contractArray[1]))
//                        {
//                            customerIdList.add(String.valueOf(map.get(contractArray[1])));
//                            break;
//                        }
//                    }
//                }
//            }
//            String[] parkingArray;
//            if ((parkingParam != null) && (!"".equals(parkingParam)))
//            {
//                Map<String, String> parMap = new HashMap();
//
//                parMap.put("start", "0");
//
//                parMap.put("rows", "300");
//
//                parkingArray = parkingParam.split(",");
//                sb = new StringBuilder();
//                sb.append(parkingArray[0]).append(":").append(searchPhrase).append(" OR ").append(parkingArray[0]).append(":*").append(searchPhrase).append("*");
//
//                parMap.put("fl", "id," + parkingArray[1]);
//                parMap.put("q", "parkProjectID:" + projectID + " AND (" + sb.toString() + ")");
//                List<Map<String, Object>> customerList = SolrManager.queryDocs(parMap);
//                logger.info("����������" + parMap);
//                logger.info("������" + (System.currentTimeMillis() - start));
//                logger.info("logcustomerList��" + customerList.size());
//                for (Map<String, Object> map : customerList)
//                {
//                    Iterator<Map.Entry<String, Object>> it2 = map.entrySet().iterator();
//                    while (it2.hasNext())
//                    {
//                        Map.Entry<String, Object> me = (Map.Entry)it2.next();
//                        if (String.valueOf(me.getKey()).contains(parkingArray[1]))
//                        {
//                            customerIdList.add(String.valueOf(map.get(parkingArray[1])));
//                            break;
//                        }
//                    }
//                }
//            }
//            if (customerIdList.size() > 0)
//            {
//                resultMap.put("customerList", customerIdList);
//                logger.info("logcustomerIdList:" + customerIdList.size());
//            }
//        }
//        catch (Exception e)
//        {
//            logger.error("error", e);
//        }
//        resultMap.put("isSolr", Integer.valueOf(1));
//        return resultMap;
//    }

//    public static Map<String, Object> solrParkRoomSearch(String searchPhrase, String projectID, String parkingParam, String isUseSolr)
//    {
//        Map<String, Object> resultMap = new HashMap();
//        if (!"1".equals(isUseSolr)) {
//            return resultMap;
//        }
//        StringBuilder sb = new StringBuilder();
//        try
//        {
//            if (StringUtils.isEmpty(searchPhrase)) {
//                return resultMap;
//            }
//            String checkSearch = searchPhrase;
//            searchPhrase = ClientUtils.escapeQueryChars(searchPhrase).toLowerCase();
//            List<String> roomIDList = new ArrayList();
//            long start = System.currentTimeMillis();
//            String[] parkingArray;
//            if ((parkingParam != null) && (!"".equals(parkingParam)))
//            {
//                Map<String, String> parMap = new HashMap();
//                parMap.put("start", "0");
//
//                parMap.put("rows", "300");
//
//                parkingArray = parkingParam.split(",");
//                sb = new StringBuilder();
//                sb.append(parkingArray[0]).append(":").append(searchPhrase).append(" OR ").append(parkingArray[0]).append(":*").append(searchPhrase).append("*");
//
//                parMap.put("fl", "id," + parkingArray[1]);
//                parMap.put("q", "parkProjectID:" + projectID + " AND (" + sb.toString() + ")");
//                List<Map<String, Object>> roomList = SolrManager.queryDocs(parMap);
//                logger.info("����������" + parMap);
//                logger.info("������" + (System.currentTimeMillis() - start));
//                logger.info("logcustomerList��" + roomList.size());
//                for (Map<String, Object> map : roomList)
//                {
//                    Iterator<Map.Entry<String, Object>> it2 = map.entrySet().iterator();
//                    while (it2.hasNext())
//                    {
//                        Map.Entry<String, Object> me = (Map.Entry)it2.next();
//                        if ((String.valueOf(me.getKey()).contains(parkingArray[1])) && (!StringUtils.isEmpty(String.valueOf(map.get(parkingArray[1])))))
//                        {
//                            roomIDList.add(String.valueOf(map.get(parkingArray[1])));
//                            break;
//                        }
//                    }
//                }
//            }
//            if (roomIDList.size() > 0) {
//                resultMap.put("roomIDList", roomIDList);
//            }
//        }
//        catch (Exception e)
//        {
//            logger.error("error", e);
//        }
//        return resultMap;
//    }

//    public static List<String> solrContractSearch(String checkSearch, String projectID, String contractParam, String rows)
//            throws Exception
//    {
//        String searchPhrase = ClientUtils.escapeQueryChars(checkSearch).toLowerCase();
//        long start = System.currentTimeMillis();
//        StringBuilder sb = new StringBuilder();
//        Map<String, String> parMap = new HashMap();
//        parMap.put("start", "0");
//        parMap.put("rows", rows);
//        String[] contractArray = contractParam.split(",");
//        for (int i = 0; i < contractArray.length; i++)
//        {
//            sb.append(contractArray[i]).append(":").append(searchPhrase).append(" OR ").append(contractArray[i]).append(":*").append(searchPhrase).append("*");
//            if ((contractArray.length > 1) && (i != contractArray.length - 1)) {
//                sb.append(" OR ");
//            }
//        }
//        parMap.put("fl", "id," + contractParam);
//        int i;
//        if (projectID.indexOf(",") != -1)
//        {
//            List<String> projectIDList = Arrays.asList(projectID.split(","));
//            StringBuilder projectSb = new StringBuilder();
//            projectSb.append("contractProjectID:").append((String)projectIDList.get(0));
//            for (i = 1; i < projectIDList.size(); i++) {
//                projectSb.append(" OR contractProjectID:").append((String)projectIDList.get(i));
//            }
//            parMap.put("q", "(" + projectSb.toString() + ") AND (" + sb.toString() + ")");
//        }
//        else
//        {
//            parMap.put("q", "contractProjectID:" + projectID + " AND (" + sb.toString() + ")");
//        }
//        List<Map<String, Object>> contractList = SolrManager.queryDocs(parMap);
//        logger.info("logcontractList��" + contractList.size());
//        logger.info("logcontractList��" + contractList);
//        List<String> contractIdList = new ArrayList();
//        for (Map<String, Object> map : contractList)
//        {
//            Iterator<Map.Entry<String, Object>> it2 = map.entrySet().iterator();
//            while (it2.hasNext())
//            {
//                Map.Entry<String, Object> me = (Map.Entry)it2.next();
//                if (String.valueOf(me.getValue()).contains(checkSearch))
//                {
//                    contractIdList.add(String.valueOf(map.get("id")));
//                    break;
//                }
//            }
//        }
//        logger.info("contractIds��" + contractIdList);
//        return contractIdList;
//    }
}
